<?php declare(strict_types=1);

namespace App\Api\V2\Controller\User;

use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\TfConfigController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\Hltx\ManageController;
use App\Api\Controllers\MyBank\MyBankController;
use App\Api\Controllers\Newland\UpdateController;
use App\Models\HltxStore;
use App\Models\MyBankStore;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\StoreWaysDesc;
use App\Models\User;
use App\Models\UserRate;
use App\Services\PrintSqlService;
use App\Services\Rate\UserRateService;
use App\Services\Store\StoreService;
use App\Services\VbillRateSaveLogService;
use App\Traits\ResponseTrait;
use App\Util\ListUtil;
use App\Util\SqlWhenUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class StoreController extends BaseController
{
    use ResponseTrait;

//店铺支付费率
    public function pay_ways_allBak(Request $request)
    {
        $user = $this->parseToken();
        $store_id = $request->get('store_id');

        $store = Store::query()->where('store_id', $store_id)
            ->select(["user_id", "store_id"])
            ->first();
        if (!$store) {
            return json_encode([
                'status' => 2,
                'message' => '门店不存在',
                'data' => []
            ]);
        }
        $data = [];
        try {
            $service = new UserRateService();
            $wxZfbYl = $service->payRateList($store, ["weixin", "alipay", "unionpay"]);
            $appletBest = $service->payRateList($store, ["Bestpay", "applet"]);
            $data = array_merge($data, $wxZfbYl, $appletBest);
            //在这里获取一个company ways_type
            $company = array_column($data, "company");
//            select  company,min(ways_type) as ways_type from  store_ways_desc group by company
            $companyWaysType = StoreWaysDesc::query()->select(["company", DB::raw("min(ways_type) as ways_type")])
                ->whereIn("company", $company)
                ->groupBy(["company"])
                ->get()->toArray();
            $companyWaysType = array_combine(array_column($companyWaysType, "company"), $companyWaysType);
            foreach ($data as $k => $v) {
                $companyV = $companyWaysType[$v["company"]] ?? [];
                $v["ways_type"] = $companyV["ways_type"];
                $data[$k] = $v;
            }
            return json_encode([
                'status' => 1,
                'data' => $data
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => '-1',
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
    }


    public function pay_ways_all(Request $request): string
    {
        $user = $this->parseToken();

        //新增通道赛选条件
        $where = [
            "company" => $request->get("company", "")
        ];

        //在这里处理权限
        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
        $systemUserArray = ListUtil::createListsNode($systemUserArray);
        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
        $userCollectionIds = array_column($userCollection, "id");
        $store_id = $request->get('store_id');
        $store = Store::query()->where('store_id', $store_id)
            ->whereIn("user_id", $userCollectionIds)
            ->select(["user_id", "store_id"])
            ->first();
        if (empty($store)) {
            return $this->errorResponse("店铺不存在");
        }
        $service = new UserRateService();
        $data = $service->payWaylists($store, $where);
        return $this->successResponse("ok", ["data" => $data]);
    }

//修改店铺支付费率
    public function edit_store_rate_pc(Request $request)
    {
        $user = $this->parseToken();
        $data = $request->all();
        $validator = Validator::make($data,
            [
                "store_id" => ["required"],
                "company" => ["required"],
                "pass" => ["required"],
//                "type" => ["required", Rule::in([1, 2])],
//                "rate" => ["required", "numeric", "between:0,1"],
                "rate_a" => ["nullable", "numeric", "between:0,1"],
                "rate_c" => ["nullable", "numeric", "between:0,1"],
                "rate_e" => ["nullable", "numeric", "between:0,1"],
                "rate_f" => ["nullable", "numeric", "between:0,1"],
                "rate_f_top" => ["nullable", "numeric", "between:0,100"],
                "rate_bestpay" => ["nullable", "numeric", "between:0,1"],  //翼支付
                "rate_wx" => ["nullable", "numeric", "between:0,1"],  //翼支付,
                "rate_alipay" => ["nullable", "numeric", "between:0,1"],  //翼支付,

                "server_rate" => ["nullable", "numeric", "between:0,1"],  //翼支付,
                "yu_rate" => ["nullable", "numeric", "between:0,1"],  //翼支付,
                "era_rate" => ["nullable", "numeric", "between:0,1"],  //翼支付,
            ], [],
            [
                "rate_bestpay" => "翼支付",  //翼支付
                "rate_wx" => "微信",  //翼支付,
                "rate_alipay" => "支付宝",  //翼支付,
                "store_id" => "店铺ID",
                "company" => "公司名称",
                "pass" => "密钥",
//                "rate" => "基础费率",
                "rate_a" => "云闪付0-1000费率",
                "rate_c" => "云闪付1000以上费率",
                "rate_e" => "刷卡信用卡费率",
                "rate_f" => "刷卡储蓄卡费率",
                "rate_f_top" => "刷卡储蓄卡封顶手续费",

                "server_rate" => "服务费模式费率",  //翼支付,
                "yu_rate" => "预充模式费率",  //翼支付,
                "era_rate" => "代扣模式费率",  //翼支付,
            ]);

        if ($validator->fails()) {
            return json_encode(['status' => 2, 'message' => $validator->errors()->first(), 'data' => []]);
        }

        //pass校验
        $pash = $request->path();
        $pass = $data["pass"];
        $pass = substr(base64_decode($pass), 0, -5);
        $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证

        $pass_verify = json_decode($pass_verify, true);
        if ($pass_verify['status'] == '1') {
            $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            $remark = $data;
            unset($remark["token"]);

            $remark = json_encode($remark);
            $remark = mb_substr($remark, 0, 255);
            $this->operation_log($this->parseToken()->user_id, 3, $remark, $pass_id);
        } else {
            return $this->errorResponse("验证不通过");
        }

        $store = Store::query()->where('store_id', $data["store_id"])->first();
        if (!$store) {
            return $this->errorResponse("门店不存在");
        }
        //共享通道不支持修改费率
        if ($user->level > 0 && $store->pay_ways_type) {
            $store_pid = Store::where('id', $store->pid)
                ->select('store_id')
                ->first();
            if (!empty($store_pid)) {
                $StorePayWay = StorePayWay::query()
                    ->select('company')
                    ->where('store_id', $store_pid->store_id)
                    ->where('company', $data["company"])
                    ->get()->toArray();
                if (!empty($StorePayWay)) {
                    return json_encode(['status' => 2, 'message' => '共享通道不支持修改费率']);
                }
            }
        }
        //

        $store_pid = $store->pid;
        $config_id = $store->config_id;

        //代理商的费率
        $user_rate = UserRate::query()
            ->select([
                "user_rates.company", "user_rates.rate", "user_rates.rate_a", "user_rates.rate_c", "user_rates.rate_e", "user_rates.rate_f",
                "user_rates.rate_f_top",
                "user_rates.era_rate",
                "user_rates.server_rate",
                "user_rates.yu_rate",
                "store_ways_desc.ways_desc",
                "store_ways_desc.ways_source",
            ])
            ->leftJoin("store_ways_desc", "user_rates.ways_type", "=", "store_ways_desc.ways_type")
            ->where("user_rates.user_id", $store->user_id)
            ->where("user_rates.company", $data["company"])
            ->where("user_rates.status", 1)
            ->get()->toArray();
        if (empty($user_rate)) {
            return $this->errorResponse("上级代理商未设置费率");
        }
        $firstUserRate = $user_rate[0];
        $user_rate = array_combine(array_column($user_rate, "ways_source"), $user_rate);
        //Bestpay "weixin", "alipay", "unionpay"
//        "rate_bestpay" => ["nullable", "numeric", "between:0,1"],  //翼支付
//                "rate_wx" => ["nullable", "numeric", "between:0,1"],  //翼支付,
//                "rate_alipay" => ["nullable", "numeric", "between:0,1"],  //翼支付,
//        "server_rate" => "服务费模式费率",  //翼支付,
//                "yu_rate" => "预充模式费率",  //翼支付,
//                "era_rate" => "代扣模式费率",  //翼支付,
        $company_config = DB::table('company_config')->where('store_id', $data["store_id"])->where('company', $data["company"])->first();
        if (empty($company_config)) {
            return $this->errorResponse("无通道配置,无法修改");
        }
        switch ((int)$company_config->model) {
            case 1: //服务费
                if (empty($data["server_rate"])) {
                    return $this->errorResponse("服务费费率必须设置");
                }
                if (!empty($firstUserRate) && $data["server_rate"] < $firstUserRate["server_rate"]) {
                    return $this->errorResponse("服务费费率不能低于代理商的费率");
                }
                break;
            case 2: //代扣
                if (empty($data["era_rate"])) {
                    return $this->errorResponse("代扣费率必须设置");
                }
                if (!empty($firstUserRate) && $data["era_rate"] < $firstUserRate["era_rate"]) {
                    return $this->errorResponse("代扣费率不能低于代理商的费率");
                }
                break;
            case 3: //通道扣费
                if (isset($user_rate["Bestpay"]) && $data["rate_bestpay"] < $user_rate["Bestpay"]["rate"]) {
                    return $this->errorResponse("翼支付费率不能低于代理商的费率");
                }

                if (isset($user_rate["weixin"]) && $data["rate_wx"] < $user_rate["weixin"]["rate"]) {
                    return $this->errorResponse("微信费率不能低于代理商的费率");
                }

                if (isset($user_rate["alipay"]) && $data["rate_alipay"] < $user_rate["alipay"]["rate"]) {
                    return $this->errorResponse("支付宝费率不能低于代理商的费率");
                }
                if (isset($user_rate["unionpay"]) && $data["rate_a"] < $user_rate["unionpay"]["rate_a"]) {
                    return $this->errorResponse("云闪付费率不能低于代理商的费率");
                }

                if (isset($user_rate["unionpay"]) && $data["rate_c"] < $user_rate["unionpay"]["rate_c"]) {
                    return $this->errorResponse("云闪付大于1000费率不能低于代理商的费率");
                }

                if (isset($user_rate["unionpay"]) && $data["rate_e"] < $user_rate["unionpay"]["rate_e"]) {
                    return $this->errorResponse("信用卡刷卡费率费率不能低于代理商的费率");
                }

                if (isset($user_rate["unionpay"]) && $data["rate_f"] < $user_rate["unionpay"]["rate_f"]) {
                    return $this->errorResponse("储蓄卡刷卡费率费率不能低于代理商的费率");
                }
                if (isset($user_rate["unionpay"]) && $data["rate_f_top"] < $user_rate["unionpay"]["rate_f_top"]) {
                    return $this->errorResponse("储蓄卡刷卡手续费上限费率费率不能低于代理商的费率");
                }
                break;
            case 4:
                if (empty($data["yu_rate"])) {
                    return $this->errorResponse("预充率必须设置");
                }
                if (!empty($firstUserRate) && $data["yu_rate"] < $firstUserRate["yu_rate"]) {
                    return $this->errorResponse("预充费率不能低于代理商的费率");
                }
                break;
        }

        $storePayWays = StorePayWay::query()
            ->select(["company", "rate", "rate_a", "rate_c", "rate_e", "rate_f", "rate_f_top", "status"])
            ->where('store_id', $data["store_id"])
            ->where('company', $data["company"])
            ->get()->toArray();
        if (empty($storePayWays)) {
            return $this->errorResponse("请先开通通道");
        }
        //开始修改费率
        $user = User::query()->where('id', $user->user_id)->first();
        if (empty($user)) {
            return $this->errorResponse("用户不存在");
        }
        try {
            $hasPermission = $user->hasPermissionTo('修改费率-' . $data["company"]);
            if (!$hasPermission) {
                return $this->errorResponse("没有权限设置费率");
            }
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
        $has = $storePayWays[0];
        $status = $has["status"];
        $status_desc = $has["status"] == 1 ? "已开通" : ($has["status"] == 0 ? "未开通" : "审核中");
        //如果通道审核中不允许修改费率
        if ($status == 2) {
            return $this->errorResponse("通道审核中不允许修改费率");
        }
        //京东收银通道修改费率
        if ($user->level > 0 && $has["status"] == 1 && $data["company"] == "jdjr") {
            return $this->errorResponse("京东通道开通后不支持软件修改");
        }
        switch ((int)$company_config->model) {
            case 1:
                //服务费
                DB::table('company_config')->where('store_id', $data["store_id"])->where('company', $data["company"])
                    ->update(['configure_channel_fee' => $data["server_rate"]]);
                //暂时全部修改
                $tmp = [
                    "receive_model" => 1,
                    "store_id" => $data["store_id"],
                    "server_rate" => "0.00",
                    "status" => $status,
                    "status_desc" => $status_desc,
                    "company" => $data["company"],
                ];

                break;
            case 2:
                DB::table('company_config')->where('store_id', $data["store_id"])->where('company', $data["company"])
                    ->update([
                        'configure_channel_fee' => $data["era_rate"]
                    ]);
                //暂时全部修改
                $tmp = [
                    "receive_model" => 2,
                    "store_id" => $data["store_id"],
                    "era_rate" => $data["era_rate"],
                    "status" => $status,
                    "status_desc" => $status_desc,
                    "company" => $data["company"],
                ];
                break;
            case 3:


                //随行付银行同步平台费率
                if ($has["status"] == 1 && $data["company"] == "vbill") {
                    $config = new VbillConfigController();

                    $vbill_config = $config->vbill_config($config_id);
                    if (!$vbill_config) {
                        return $this->errorResponse("随行付配置不存在请检查配置");
                    }
                    $vbill_merchant = $config->vbill_merchant($data["store_id"], $store_pid);
                    if (!$vbill_merchant) {
                        return $this->errorResponse("随行付商户号不存在");
                    }

                    $obj = new \App\Api\Controllers\Vbill\BaseController();
                    $dataVbill = [
                        'orgId' => $vbill_config->orgId,
                        'reqId' => time(),
                        'version' => '1.0',
                        'timestamp' => date('Ymdhis', time()),
                        'signType' => 'RSA',
                        'reqData' => [
                            'mno' => $vbill_merchant->mno, //商户编号
                            'qrcodeList' => [
                                [
                                    'rateType' => '01', //微信
                                    'rate' => $data["rate_wx"],
                                ],
                                [
                                    'rateType' => '02', //支付宝
                                    'rate' => $data["rate_alipay"],
                                ],
                                [
                                    'rateType' => '06', //银联单笔小于等于1000
                                    'rate' => $data["rate_a"],
                                ],
                                [
                                    'rateType' => '07', //银联单笔大于1000
                                    'rate' => $data["rate_c"],
                                ]
                            ]
                        ],
                    ];
                    $url = $obj->update_rate;
                    $re = $obj->execute($dataVbill, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
                    //系统错误
                    if ($re['data']['respData']['bizCode'] != '0000') {
                        return $this->errorResponse($re['data']['respData'] ['bizMsg']);
                    }

                    /**
                     * 待入库修改数据
                     */
                    $tmp = [
                        "receive_model" => 3,
                        "store_id" => $data["store_id"],
                        "rate_bestpay" => $data["rate_bestpay"],  //翼支付
                        "rate_wx" => $data["rate_wx"], //翼支付,
                        "rate_alipay" => $data["rate_alipay"], //翼支付,
                        "status" => $status,
                        "status_desc" => $status_desc,
                        "company" => $data["company"],
                        "rate_a" => $data["rate_a"],
                        "rate_c" => $data["rate_c"],
                        "rate_e" => $data["rate_e"],
                        "rate_f" => $data["rate_f"],
                        "rate_f_top" => $data["rate_f_top"],
                    ];

                    /**
                     * 保存随行付次日生效数据
                     */
                    $log = [
                        'store_id' => $data['store_id'],
                        'rate_wx'=>$data["rate_wx"],
                        'rate_alipay'=>$data["rate_alipay"],
                        'rate_a'=>$data["rate_a"],
                        'rate_c'=>$data["rate_c"],
                        'uid'=>$user->id,
                        'save_param'=>json_encode($tmp),
                        'org_id' => $vbill_config->orgId,
                        'mno' => $vbill_merchant->mno,
                        'privateKey'=>$vbill_config->privateKey,
                        'sxfpublic'=>$vbill_config->sxfpublic,
                    ];
                    $queryWhere = [
                        "store_id" => $data["store_id"],
                        "mno" => $vbill_merchant->mno,
                        'status'=>0,
                    ];
                    $logData = VbillRateSaveLogService::getInstance()->getQueryData($queryWhere);
                    if($logData->isEmpty())
                    {
                        $saveId = 0;
                    }else{
                        $info = $logData->toArray();
                        $saveId = $info[0]['id'];
                    }

                    $logResult = VbillRateSaveLogService::getInstance()->saveData($log,$saveId);
                    if (empty($logResult))
                        return $this->errorResponse('修改失败');
                    
                    return [
                        'status' => 1,
                        'message' => '修改成功',
                    ];
                }
                //随行付a银行同步平台费率
                if ($has["status"] == 1 && $data["company"] == "vbilla") {
                    $config = new VbillConfigController();
                    $vbill_config = $config->vbilla_config($config_id);
                    if (!$vbill_config) {
                        return $this->errorResponse("随行付配置不存在请检查配置");
                    }
                    $vbill_merchant = $config->vbilla_merchant($data["store_id"], $store_pid);
                    if (!$vbill_merchant) {
                        return $this->errorResponse("随行付商户号不存在");
                    }

                    $obj = new \App\Api\Controllers\Vbill\BaseController();
                    $dataVbilla = [
                        'orgId' => $vbill_config->orgId,
                        'reqId' => time(),
                        'version' => '1.0',
                        'timestamp' => date('Ymdhis', time()),
                        'signType' => 'RSA',
                        'reqData' => [
                            'mno' => $vbill_merchant->mno,//商户编号
                            'qrcodeList' => [
                                [
                                    'rateType' => '01',
                                    'rate' => $data["rate_wx"],
                                ],
                                [
                                    'rateType' => '02',
                                    'rate' => $data["rate_alipay"],
                                ],
                                [
                                    'rateType' => '06',
                                    'rate' => $data["rate_a"],
                                ],
                                [
                                    'rateType' => '07',
                                    'rate' => $data["rate_c"],
                                ]
                            ]
                        ],
                    ];
                    $url = $obj->update_rate;
                    $re = $obj->execute($dataVbilla, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
                    //系统错误
                    if ($re['data']['respData']['bizCode'] != '0000') {
                        return $this->errorResponse($re['data']['respData'] ['bizMsg']);
                    }

                }
                $tmp = [
                    "receive_model" => 3,
                    "store_id" => $data["store_id"],
                    "rate_bestpay" => $data["rate_bestpay"],  //翼支付
                    "rate_wx" => $data["rate_wx"], //翼支付,
                    "rate_alipay" => $data["rate_alipay"], //翼支付,
                    "status" => $status,
                    "status_desc" => $status_desc,
                    "company" => $data["company"],
                    "rate_a" => $data["rate_a"],
                    "rate_c" => $data["rate_c"],
                    "rate_e" => $data["rate_e"],
                    "rate_f" => $data["rate_f"],
                    "rate_f_top" => $data["rate_f_top"],
                ];
                $this->send_ways_data((int)$company_config->model, $tmp);
                return [
                    'status' => 1,
                    'message' => '修改成功',
                ];
            case 4:
                DB::table('company_config')->where('store_id', $data["store_id"])->where('company', $data["company"])->update([
                    'configure_channel_fee' => $data["yu_rate"]
                ]);
                DB::table('server_stores')->where('store_id', $data["store_id"])->where('company', $data["company"])
                    ->update(['rata_store' => $data["yu_rate"]]);
                DB::table('stores')->where('store_id', $data["store_id"])->update([
                    "is_sign" => 1,
                    'rata_store' => $data["yu_rate"]
                ]);
                //预充费率修改
                $tmp = [
                    "receive_model" => 4,
                    "store_id" => $data["store_id"],
                    "yu_rate" => "0.00",
                    "status" => $status,
                    "status_desc" => $status_desc,
                    "company" => $data["company"],
                ];
                break;
        }

        $this->send_ways_data((int)$company_config->model, $tmp);
        return [
            'status' => 1,
            'message' => '修改成功',
        ];
    }

    //修改费率
    public function send_ways_data(int $receiveModel, array $data): void
    {
        //修改费率- 修改一个通道下的所有支付方式
        $companyWaysDesc = StoreWaysDesc::query()->where("company", $data["company"])->get()->toArray();
        $companyPayWays = StorePayWay::query()->where("store_id", $data["store_id"])->where("company", $data["company"])->get()->toArray();
        $companyPayWays = array_combine(array_column($companyPayWays, "ways_source"), $companyPayWays);
        $updated = $created = [];
        foreach ($companyWaysDesc as $waysDesc) {
            //判断扣费模式
            switch ($receiveModel) {
                case 1:
                    $rate = $data["server_rate"];
                    break;
                case 2:
                    $rate = $data["era_rate"];
                    break;
                case 3:
                    //Bestpay "weixin", "alipay", "unionpay"
                    if ($waysDesc["ways_source"] == "weixin") {
                        $rate = $data["rate_wx"];
                    } else if ($waysDesc["ways_source"] == "alipay") {
                        $rate = $data["rate_alipay"];
                    } else if ($waysDesc["ways_source"] == "unionpay") {
                        $rate = $data["rate_a"];
                    } else if ($waysDesc["ways_source"] == "Bestpay") {
                        $rate = $data["rate_bestpay"];
                    } else if ($waysDesc["ways_source"] == "jd") {
                        $rate["rate"] = $data["rate_wx"];
                    } else if ($waysDesc["ways_source"] == "applet") {
                        $rate["rate"] = $data["rate_wx"];
                    }
                    break;
                case 4:
                    $rate = $data["yu_rate"];
                    break;
            }
            if (isset($companyPayWays[$waysDesc["ways_source"]])) {
                //更新数据
//                dd($companyPayWays[$waysDesc["ways_source"]]);
                $updated[] = [
                    "id" => $companyPayWays[$waysDesc["ways_source"]]["id"],
//                    'store_id' => $data['store_id'],
//                    'ways_type' => $waysDesc["ways_type"],
//                    'company' => $waysDesc["company"],
//                    'ways_source' => $waysDesc["ways_source"],
//                    'ways_desc' => $waysDesc["ways_desc"],
                    'rate' => $rate,
                    'settlement_type' => $waysDesc["settlement_type"],
                    'status' => $data['status'],
                    'status_desc' => $data['status_desc'],
                    "rate_a" => $data["rate_a"] ?? $companyPayWays[$waysDesc["ways_source"]]["rate_a"],
                    "rate_c" => $data["rate_c"] ?? $companyPayWays[$waysDesc["ways_source"]]["rate_c"],
                    "rate_e" => $data["rate_e"] ?? $companyPayWays[$waysDesc["ways_source"]]["rate_e"],
                    "rate_f" => $data["rate_f"] ?? $companyPayWays[$waysDesc["ways_source"]]["rate_f"],
                    "rate_f_top" => $data["rate_f_top"] ?? $companyPayWays[$waysDesc["ways_source"]]["rate_f_top"],
                ];
            } else {
                //新增数据
                $created[] = [
                    'store_id' => $data['store_id'],
                    'ways_type' => $waysDesc["ways_type"],
                    'company' => $waysDesc["company"],
                    'ways_source' => $waysDesc["ways_source"],
                    'ways_desc' => $waysDesc["ways_desc"],
                    'rate' => $rate,
                    'settlement_type' => $waysDesc["settlement_type"],
                    'status' => $data['status'],
                    'status_desc' => $data['status_desc'],
                    "rate_a" => $data["rate_a"] ?? $waysDesc["rate_a"],
                    "rate_c" => $data["rate_c"] ?? $waysDesc["rate_c"],
                    "rate_e" => $data["rate_e"] ?? $waysDesc["rate_e"],
                    "rate_f" => $data["rate_f"] ?? $waysDesc["rate_f"],
                    "rate_f_top" => $data["rate_f_top"] ?? $waysDesc["rate_f_top"],
                ];
            }
        }
//        PrintSqlService::listen();
//        dump($updated);
        //更新通道
        if (!empty($updated)) {
            //执行批量 使用 case when 批量更新数据
            //执行更新sql
            $util = new SqlWhenUtil();
            list($whereValue, $updatedRaw) = $util->caseSql($updated, "id");
            StorePayWay::query()->whereIn("id", $whereValue)->update($updatedRaw);
        }
        //新增通道
        if (!empty($created)) {
            StorePayWay::query()->insert($created);
        }
    }

    //查看店铺的成本费率
    public function getUserRateList(Request $request): string
    {
        $store_id = $request->get("store_id");
        $company = $request->get("company");
        $user = $this->parseToken();
        try {
            //查看代理商是否存在权限
            $userArray = User::query()->select("id", "pid", "name")->get()->toArray();
            $systemUserArray = ListUtil::createListsNode($userArray);
            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
            $userCollectionIds = array_column($userCollection, "id");

            $store = Store::query()->where("store_id", $store_id)->whereIn("user_id", $userCollectionIds)->first();
            if (empty($store)) {
                throw new \Exception("店铺不存在");
            }
            //判断支付方式
//            if (!StorePayWay::query()->where([
//                "company" => $company,
//                "store_id" => $store->store_id,
//                "status" => 1
//            ])->exists()) {
//                throw new \Exception("店铺支付通道不存在");
//            }

            $storeUserId = $store->user_id;
//            prevGetTreeNode
            $systemUserArray = ListUtil::createTreeNode($userArray);
            $prevUserList = ListUtil::prevGetTreeNode($systemUserArray, ["id" => $storeUserId]);
            $service = new StoreService();
            $userrateList = $service->getUserRateList($company, $prevUserList);
            return $this->successResponse("ok", ["data" => $userrateList]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


}